package com.eportal.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.aop.WriteOperateLog;
import com.eportal.base.BaseDAO;
import com.eportal.domain.PayDetail;
import com.eportal.domain.PayRedEnvRule;
import com.eportal.domain.PayWallet;
import com.eportal.domain.Sysopt;
import com.eportal.service.BannerStrategyService;
import com.eportal.service.PayRedEnvRuleService;
import com.eportal.service.SysmenuService;
import com.eportal.util.DateUtils;
import com.framework.jqgrid.JqGridPager;

/**
 * payRedEnvRuleServiceImpl
 * @author chencheng
 */

@Service("payRedEnvRuleServiceImpl")
public class PayRedEnvRuleServiceImpl  implements PayRedEnvRuleService {
	 private Logger log = Logger.getLogger(PayRedEnvRuleServiceImpl.class);
	 private Map<String, Object> result = new HashMap<String, Object>();
	 
	 @Resource(name="dao")
	 private BaseDAO dao;
	 @Resource(name="sysmenuService")
	 private SysmenuService sysmenuService;
	 @Autowired
	 private BannerStrategyService bannerStrategyService;
	 
    @Override
    public Object save(Object obj) throws Exception {
    	dao.save(obj);
    	return obj;
    }

    @Override
    public Object get(Class clazz,Long id) {
        return  dao.getById(clazz, id);
    }

    @Override
    public Object get(String hql) {
		return  dao.loadObject(hql);
	}
    
    @Override
    public void update(Object entity) throws Exception {
    	try {
    		dao.update(entity);
        } catch (Exception e) {
            log.error(this,e);
        }
        
    }

    
	
    public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	/**
     * 红包保存
     */
    @LogAnnotation(operateDescribe="红包保存")  
    public Map<String, Object> addPayRedEnvRuleMethod(String showTime, String expiredTime,PayRedEnvRule payRedEnvRule) {
         try {
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	payRedEnvRule.setAgtCode(user.getAgtCode());
        	String rType = payRedEnvRule.getrType();
        	if ("0".equals(rType)) {//金额平均
        		BigDecimal avgAmount = payRedEnvRule.getAvgAmount();
        		int cNum = payRedEnvRule.getcNum();
        		BigDecimal amount = avgAmount.multiply(new BigDecimal(cNum));
        		payRedEnvRule.setAmount(amount);
			}
			PayWallet payWallet = getPayWallet(user.getAgtCode());
			if(payWallet == null){
				result.put("code", 0);
		        result.put("msg", "该公司钱包余额不足。请充值！");
		        return result;
			}
        	BigDecimal balance = payWallet.getAmount().subtract(payRedEnvRule.getAmount());
			int i=balance.compareTo(BigDecimal.ZERO); 
			if(i==-1){ 
				result.put("code", 0);
		        result.put("msg", "该公司钱包余额不足。请充值！");
		        return result;
			}
        	
        	String range = payRedEnvRule.getRange();
        	if("2".equals(range)){
//        		String communityIds = bannerStrategyService.getCommunityId(payRedEnvRule.getAgtCode());
//        		payRedEnvRule.setAcceptCommunityId(","+communityIds+",");
//        	}else {
        		payRedEnvRule.setAcceptCommunityId(","+payRedEnvRule.getAcceptCommunityId().trim().replace(" ", "")+",");
			}
        	StringBuffer sb = new StringBuffer(DateUtils.currentDate());
        	sb.append(" ");
        	sb.append(showTime);
        	sb.append(":00");
        	payRedEnvRule.setTimeStart(Timestamp.valueOf(sb.toString()));
        	sb = new StringBuffer(DateUtils.currentDate());
        	sb.append(" ");
        	sb.append(expiredTime);
        	sb.append(":00");
        	payRedEnvRule.setTimeEnd(Timestamp.valueOf(sb.toString()));
        	payRedEnvRule.setrStatus("0");
        	payRedEnvRule.setAuditStatus("0");
        	payRedEnvRule.setCreateType("1");
        	payRedEnvRule.setcTime(new Timestamp(System.currentTimeMillis()));
        	payRedEnvRule.setcUserName(Long.toString(user.getSid()));
        	save(payRedEnvRule);
        	result.put("objectId", payRedEnvRule.getSid());
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("红包保存失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
    }
    
    /**
     * 钱包查询
     */
    public PayWallet getPayWallet(String agtCode) {
    	StringBuffer sb = new StringBuffer("from PayWallet where uType='1' and userId='");
		sb.append(agtCode);
		sb.append("'");
		PayWallet payWallet = (PayWallet) get(sb.toString());
		return payWallet;
	}

	/**
     * 红包规则更新保存
     */
    @Override
    @LogAnnotation(operateDescribe="红包规则更新")  
	public Map<String, Object> updatePayRedEnvRuleMethod(String showTime, String expiredTime,
			PayRedEnvRule payRedEnvRule) {
    	result.put("objectId", payRedEnvRule.getSid());
    	try {
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    		String rType = payRedEnvRule.getrType();
        	PayRedEnvRule entity = (PayRedEnvRule) get(PayRedEnvRule.class, payRedEnvRule.getSid());
        	entity.setrName(payRedEnvRule.getrName());
        	entity.setcNum(payRedEnvRule.getcNum());
        	entity.setrType(rType);
        	if ("0".equals(rType)) {//金额平均
        		BigDecimal avgAmount = payRedEnvRule.getAvgAmount();
        		int cNum = payRedEnvRule.getcNum();
        		entity.setAmount(avgAmount.multiply(new BigDecimal(cNum)));
        		entity.setAvgAmount(avgAmount);
			}else{
				entity.setAmount(payRedEnvRule.getAmount());
				entity.setMinAmount(payRedEnvRule.getMinAmount());
			}
        	PayWallet payWallet = getPayWallet(user.getAgtCode());
			if(payWallet == null){
				result.put("code", 0);
		        result.put("msg", "该公司钱包余额不足。请充值！");
		        return result;
			}
        	BigDecimal balance = payWallet.getAmount().subtract(payRedEnvRule.getAmount());
			int i=balance.compareTo(BigDecimal.ZERO); 
			if(i==-1){ 
				result.put("code", 0);
		        result.put("msg", "该公司钱包余额不足。请充值！");
		        return result;
			}
        	entity.setLimitNum(payRedEnvRule.getLimitNum());
        	entity.setRange(payRedEnvRule.getRange());
        	if("1".equals(payRedEnvRule.getRange())){
        		String communityIds = bannerStrategyService.getCommunityId(payRedEnvRule.getAgtCode());
        		entity.setAcceptCommunityId(","+communityIds+",");
        	}else {
        		entity.setAcceptCommunityId(","+payRedEnvRule.getAcceptCommunityId().trim().replace(" ", "")+",");
			}
        	entity.setDateStart(payRedEnvRule.getDateStart());
        	entity.setDateStart(payRedEnvRule.getDateStart());
        	StringBuffer sb = new StringBuffer(DateUtils.currentDate());
        	sb.append(" ");
        	sb.append(showTime);
        	sb.append(":00");
        	entity.setTimeStart(Timestamp.valueOf(sb.toString()));
        	sb = new StringBuffer(DateUtils.currentDate());
        	sb.append(" ");
        	sb.append(expiredTime);
        	sb.append(":00");
        	entity.setTimeEnd(Timestamp.valueOf(sb.toString()));
//        	payRedEnvRule.setrStatus("0");
//        	payRedEnvRule.setAuditStatus("0");
//        	payRedEnvRule.setCreateType("1");
//        	entity.setcTime(new Timestamp(System.currentTimeMillis()));
//        	entity.setcUserName(Long.toString(user.getSid()));
        	update(entity);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("红包保存失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
	}
	
   
	@Override
	public List<Map<String, Object>> list(JqGridPager jqGridPager, StringBuffer sql) {
		return dao.query(sql.toString(), jqGridPager);
	}

	/**
	 * 红包上线
	 */
	@Override
	@LogAnnotation(operateDescribe="红包上线")  
	public Map<String, Object> upMethod(String sid,String redId) {
		result.put("objectId", sid);
    	try {
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	PayRedEnvRule entity = (PayRedEnvRule) get(PayRedEnvRule.class, Long.parseLong(sid));
        	//用户钱包
        	PayWallet payWallet = getPayWallet(entity.getAcceptAgtCode());
        	if(payWallet == null){
        		result.put("code", 0);
                result.put("msg", "用户查询余额为零，请充值");
                return result;
			}
        	//红包规则
        	entity.setAuditStatus("1");
        	entity.setThridRedId(redId);
        	entity.setaUserName(Long.toString(user.getSid()));
        	entity.setaTime(new Timestamp(System.currentTimeMillis()));
        	
        	//交易记录
        	PayDetail payDetail = new PayDetail();
			payDetail.setAmount(entity.getAmount());
			payDetail.setcTime(new Timestamp(System.currentTimeMillis()));
			payDetail.setDetailSubject("");
			payDetail.setdType("3");
			payDetail.setGeneralSubject("红包");
			payDetail.setDetailSubject("红包");
			payDetail.setComm("红包上线扣除金额");
			HttpServletRequest request = ServletActionContext.getRequest();
			payDetail.setIpAdd(WriteOperateLog.getIpAddr(request));
			payDetail.setOptId(Long.toString(user.getSid()));
			payDetail.setWalletId(Long.toString(payWallet.getSid()));
			//交易前金额
			payDetail.setPreAmount(payWallet.getAmount());
			//计算余额
        	BigDecimal balance = payWallet.getAmount().subtract(entity.getAmount());
			int i=balance.compareTo(BigDecimal.ZERO); 
			if(i==-1){ 
				result.put("code", 0);
		        result.put("msg", "该公司钱包余额不足。请充值！");
		        return result;
			}
			//钱包余额修改
			payWallet.setAmount(balance);
			
			save(payDetail);
        	update(payWallet);
        	update(entity);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("红包上线保存失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
	}

	/**
	 * 红包下线
	 */
	@Override
	@LogAnnotation(operateDescribe="红包下线")  
	public Map<String, Object> offMethod(String sid) {
		result.put("objectId", sid);
    	try {
    		//红包规则
        	PayRedEnvRule entity = (PayRedEnvRule) get(PayRedEnvRule.class, Long.parseLong(sid));
        	if(entity==null){
        		 result.put("code", 0);
                 result.put("msg", "查询红包规则不存在，请刷新");
                 return result;
        	}
        	entity.setrStatus("1");
        	
        	//钱包
        	PayWallet payWallet = getPayWallet(entity.getAcceptAgtCode());
        	BigDecimal balance;
        	if(entity.getSendAmount() == null){
        		balance= entity.getAmount();
        	}else{
        		//计算余额,红包金额减去已发送的金额
        		int i=entity.getSendAmount().compareTo(BigDecimal.ZERO); 
        		if(i==-1){ 
        			balance= entity.getAmount();
        		}else{
        			balance = entity.getAmount().subtract(entity.getSendAmount());
        		}
        	}
			
        	//交易记录
        	PayDetail payDetail = new PayDetail();
			payDetail.setAmount(balance);
			payDetail.setcTime(new Timestamp(System.currentTimeMillis()));
			payDetail.setDetailSubject("");
			payDetail.setdType("1");
			payDetail.setGeneralSubject("红包");
			payDetail.setDetailSubject("红包剩余金额返回钱包");
			payDetail.setComm("红包剩余金额返回钱包");
			HttpServletRequest request = ServletActionContext.getRequest();
			payDetail.setIpAdd(WriteOperateLog.getIpAddr(request));
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			payDetail.setOptId(Long.toString(user.getSid()));
			payDetail.setWalletId(Long.toString(payWallet.getSid()));
			//交易前金额
			payDetail.setPreAmount(payWallet.getAmount());
        	
        	//返回钱包
			payWallet.setAmount(payWallet.getAmount().add(balance));
			update(payWallet);
			save(payDetail);
			update(entity);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("红包上线保存失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
	}

	/**
	 * 充值提现
	 */
	@Override
	@LogAnnotation(operateDescribe="充值提现")  
	public Map<String, Object> rechargeMethod(String type, String agtCode, String changeAmount,String comm) {
		try {
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			PayDetail payDetail = new PayDetail();
			payDetail.setComm(comm);
			
			payDetail.setcTime(new Timestamp(System.currentTimeMillis()));
			payDetail.setDetailSubject("");
			payDetail.setdType(type);
			if ("1".equals(type)) {
				payDetail.setGeneralSubject("充值");
				payDetail.setDetailSubject("充值");
			}else{
				payDetail.setGeneralSubject("提现");
				payDetail.setDetailSubject("提现");
			}
			HttpServletRequest request = ServletActionContext.getRequest();
			payDetail.setIpAdd(WriteOperateLog.getIpAddr(request));
			payDetail.setOptId(Long.toString(user.getSid()));
	//		payDetail.setFromWalletId(fromWalletId);
			
			PayWallet payWallet =  getPayWallet(agtCode);
			if (payWallet == null) {
				if ("1".equals(type)) {
					payDetail.setAmount(new BigDecimal("+"+changeAmount));
					payDetail.setPreAmount(new BigDecimal("0.00"));
					payWallet = new PayWallet();
					payWallet.setuType("1");
					payWallet.setUserId(agtCode);
					payWallet.setAmount(new BigDecimal(changeAmount));
					payWallet.setwStatus("1");
					payWallet.setcTime(new Timestamp(System.currentTimeMillis()));
				}else{
					 result.put("code", 0);
			         result.put("msg", "该公司未开通钱包，金额为零。无法提现");
			         return result;
				}
				save(payWallet);
			}else{
				BigDecimal preAmount = payWallet.getAmount();
				payDetail.setPreAmount(preAmount);
				if ("1".equals(type)) {
					payDetail.setAmount(new BigDecimal("+"+changeAmount));
					payWallet.setAmount(preAmount.add(new BigDecimal(changeAmount)));
				}else{
					payDetail.setAmount(new BigDecimal("-"+changeAmount));
					BigDecimal amount = preAmount.subtract(new BigDecimal(changeAmount));
					int i=amount.compareTo(BigDecimal.ZERO); 
					if(i==-1){ 
						result.put("code", 0);
				        result.put("msg", "该公司钱包余额小于提现金额。请重新输入提现金额");
				        return result;
					}
					payWallet.setAmount(amount);
				}
				update(payWallet);
			}
			payDetail.setWalletId(Long.toString(payWallet.getSid()));
		
			save(payDetail);
			result.put("code", 1);
	        result.put("msg", "操作成功");
		} catch (Exception e) {
			 log.error("钱包充值或提现失败", e);
	         result.put("code", 0);
	         result.put("msg", "操作失败");
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> countQuery(String sql) {
		List<Map<String, Object>>   list  = dao.queryBySql(sql);
		return list;
	}
	
	


}
